<?php
namespace app\api\controller;

use app\common\model\Banner;
use app\common\model\Topic;
use app\common\model\TopicCate;
use app\common\model\TopicLog;
use app\common\model\User;
use app\common\model\UserDistribution;
use app\common\model\UserPrice;
use app\common\services\WechatService;
use app\logic\QqxcxLogic;
use app\logic\TopicLogic;
use app\logic\UserLogic;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\facade\Request;

class Index
{
    /**
     * 列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $pageSize = Request::param('pageSize',10);
        //获取8个热门爆款
        $hostList = Topic::where(['is_deleted'=>0,'is_publish'=>1,'is_recommend'=>1])
            ->order(['weight'=>'asc','created_at'=>'desc'])
            ->limit(8)->field(['topic_id','banner_img','share_img','title'])->select()->toArray();

        //获取8个上新测试
        $newList = Topic::where(['is_deleted'=>0,'is_publish'=>1,'icon_type'=>1])
            ->order(['weight'=>'asc','created_at'=>'desc'])
            ->limit(8)->field(['topic_id','banner_img','share_img','title'])->select()->toArray();

        //其他的进行分页处理
        $topicList = Topic::where(['is_deleted'=>0,'is_publish'=>1])
//            ->whereNotIn('topic_id',array_column($topList,'topic_id'))
            ->order(['weight'=>'asc','created_at'=>'desc'])
            ->field(['topic_id','banner_img','share_img','title','description','icon_type','base_game_count'])->paginate($pageSize)->toArray();

        if($hostList){
            foreach ($hostList as &$v){
                $v['banner_img'] = getThumbImg($v['banner_img'],400);
                $v['share_img'] = getThumbImg($v['share_img'],400);
            }
            unset($v);
        }
        if($newList){
            foreach ($newList as &$v){
                $v['banner_img'] = getThumbImg($v['banner_img'],400);
                $v['share_img'] = getThumbImg($v['share_img'],400);
            }
            unset($v);
        }
        if($topicList['data']){
            $ids = array_column($topicList['data'],'topic_id');
            $topicTotalLog = TopicLog::whereIn("topic_id",$ids)->field(['topic_id','count(user_id) as count'])->group('topic_id')->select()->toArray();
            foreach ($topicList['data'] as &$v){
                $v['game_count'] = $v['base_game_count'] * rand(5,10);
                if($topicTotalLog){
                    foreach ($topicTotalLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){ $v['game_count'] = ($log['count']+$v['base_game_count'])* rand(5,10);break;}
                    }
                    unset($log);
                }
                if($v['game_count'] > 10000){$v['game_count'] = sprintf("%01.2f",$v['game_count']/10000).'万';}
                $v['banner_img'] = getThumbImg($v['banner_img'],400);
                $v['share_img'] = getThumbImg($v['share_img'],400);
                $v['icon'] = !empty($v['icon_type'])? Config::get('params.php_server') . '/static/images/icon_' . $v['icon_type'] .'.png' : '';
                unset($v['base_game_count']);
            }
        }

        //获取广告位信息
        $banner = Banner::where(['is_deleted'=>0])->order("id","desc")
            ->field('banner_img,topic_id')->select()
            ->toArray();
        if($banner){
            foreach ($banner as &$v){
                $v['banner_img'] = getThumbImg($v['banner_img'],400);
            }
            unset($v);
        }
        wapAjaxReturn(0,'查询成功',['hostList'=>$hostList,'newList'=>$newList,'topicList'=>$topicList,'show_video'=>Config::get('params.tt_show_video'),
            'banner'=>$banner]);
    }

    /**
     * 关键词搜索
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function search()
    {
        $pageSize = Request::param('pageSize',10);
        $keyword = Request::param('keyword','');
        //其他的进行分页处理
        $topicList = Topic::where(['is_deleted'=>0,'is_publish'=>1])
            ->where('title','like',"%{$keyword}%")
            ->order(['weight'=>'asc','created_at'=>'desc'])
            ->field(['topic_id','banner_img','share_img','title','description','icon_type','base_game_count'])->paginate($pageSize)->toArray();

        if($topicList['data']){
            $ids = array_column($topicList['data'],'topic_id');
            $topicTotalLog = TopicLog::whereIn("topic_id",$ids)->field(['topic_id','count(user_id) as count'])->group('topic_id')->select()->toArray();
            foreach ($topicList['data'] as &$v){
                $v['game_count'] = $v['base_game_count'] * rand(5,10);
                if($topicTotalLog){
                    foreach ($topicTotalLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){ $v['game_count'] = ($log['count']+$v['base_game_count'])* rand(5,10);break;}
                    }
                    unset($log);
                }
                if($v['game_count'] > 10000){$v['game_count'] = sprintf("%01.2f",$v['game_count']/10000).'万';}
                $v['banner_img'] = getThumbImg($v['banner_img'],400);
                $v['share_img'] = getThumbImg($v['share_img'],400);
                $v['icon'] = !empty($v['icon_type'])? Config::get('params.php_server') . '/static/images/icon_' . $v['icon_type'] .'.png' : '';
                unset($v['base_game_count']);
            }
        }
        wapAjaxReturn(0,'查询成功',$topicList);
    }

    /**
     * 分类搜索
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cateSearch()
    {
        $pageSize = Request::param('pageSize',10);
        $cateId = Request::param('cateId','');
		
        if($cateId){
            //其他的进行分页处理
        $topicList = Topic::where(['is_deleted'=>0,'is_publish'=>1])
            ->where('category','=',$cateId)
            ->order(['weight'=>'asc','created_at'=>'desc'])
            ->field(['topic_id','banner_img','title','description','icon_type','base_game_count'])->paginate($pageSize)->toArray();
        }else{
            //其他的进行分页处理
        $topicList = Topic::where(['is_deleted'=>0,'is_publish'=>1])
            ->order(['weight'=>'asc','created_at'=>'desc'])
            ->field(['topic_id','banner_img','title','description','icon_type','base_game_count'])->paginate($pageSize)->toArray();
        }
		
        if($topicList['data']){
            $ids = array_column($topicList['data'],'topic_id');
            $topicTotalLog = TopicLog::whereIn("topic_id",$ids)->field(['topic_id','count(user_id) as count'])->group('topic_id')->select()->toArray();
            foreach ($topicList['data'] as &$v){
                $v['game_count'] = $v['base_game_count'] * rand(5,10);
                if($topicTotalLog){
                    foreach ($topicTotalLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){ $v['game_count'] = ($log['count']+$v['base_game_count'])* rand(5,10);break;}
                    }
                    unset($log);
                }
                if($v['game_count'] > 10000){$v['game_count'] = sprintf("%01.2f",$v['game_count']/10000).'万';}
                $v['banner_img'] = getThumbImg($v['banner_img'],400);
                $v['icon'] = !empty($v['icon_type'])? Config::get('params.php_server') . '/static/images/icon_' . $v['icon_type'] .'.png' : '';
                unset($v['base_game_count']);
            }
        }
        wapAjaxReturn(0,'查询成功',$topicList);
    }

    /**
     * 获取openid
     */
    public function getOpenId(){
        $code = Request::param('code','');
        $platform = Request::param('platform',1);
        $parentOpenid = Request::param('parentOpenid','');
        file_put_contents('openid.log',date('Y-m-d H:i:s')."\r\n",FILE_APPEND);
        file_put_contents('openid.log',$code."\r\n",FILE_APPEND);
        file_put_contents('openid.log',$platform."\r\n",FILE_APPEND);
        file_put_contents('openid.log',$parentOpenid."\r\n",FILE_APPEND);
        file_put_contents('openid.log','-----------------'."\r\n",FILE_APPEND);
        empty($code)?wapAjaxReturn(400,'参数错误'):'';

        try{

        //调用qq小程序后端端口api获取openid
        $res = json_decode((new QqxcxLogic())->getCode2Session($code,$platform),true);
        if(empty($res['session_key'])){
            wapAjaxReturn(400,'凭证已经失效',$res);
        }
        //存储数据库，openid信息
        $saveUser = (new UserLogic())->saveOpenid($res['openid'],$platform,$parentOpenid);
        if(!$saveUser['error']){
            wapAjaxReturn(0,'处理成功',['openid'=>$res['openid'],'session_key'=>$res['session_key'],'has_info'=>$saveUser['hasInfo']]);
        }
        wapAjaxReturn(400,'操作失败');
        }catch (Exception $exception){
            wapAjaxReturn(400,$exception->getMessage());
        }
    }

    /**
     * 绑定分销关系
     */
    public function bindDistribution(){
        $params = Request::get();
        file_put_contents('bind2.log',date('Y-m-d H:i:s').print_r($params,1)."\r\n",FILE_APPEND);
        if(empty($params['openid'])){wapAjaxReturn(400,'没有openid');}
        if(empty($params['platform'])){wapAjaxReturn(400,'没有platform');}
//        if(empty($params['parentOpenid'])){wapAjaxReturn(400,'没有parentOpenid');}

        if(!empty($params['parentOpenid']) && $params['openid'] != $params['parentOpenid']){
            //存储数据库，openid信息
            $saveUser = (new UserLogic())->saveOpenid($params['openid'],$params['platform'],$params['parentOpenid']);
            if(!$saveUser['error']){
                wapAjaxReturn(0,'处理成功');
            }
            wapAjaxReturn(400,'操作失败');
        }
        wapAjaxReturn(0,'无需操作，自己进入的');

    }

    /**
     * 存储用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function saveUserInfo(){
        $params = Request::get();
        if(empty($params['openid'])){wapAjaxReturn(500,'缺少openid');}
        $userInfo = User::where('openid',$params['openid'])->find();
        if(empty($userInfo)){wapAjaxReturn(500,'用户信息不存在');}
        try{

            //存储数据库，openid信息
            $saveUser = (new UserLogic())->saveUserInfo($params);
            if($saveUser){
                wapAjaxReturn(0,'处理成功');
            }
            wapAjaxReturn(400,'操作失败');
        }catch (Exception $exception){
            wapAjaxReturn(400,$exception->getMessage());
        }
    }

    /**
     * 获取测评数据
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTopicDetail(){
        $topicId = Request::param('topic_id',0);
        if(empty($topicId)||!is_numeric($topicId+0)||$topicId<0){
            wapAjaxReturn(400,'数据不对');
        }
        $topicInfo = \app\common\model\Topic::with(['questions'])
            ->where('topic_id',$topicId)
            ->field(['topic_id','title','description','banner_img','topic','nickname_attr','headerimg_attr','share_content','need_share','share_img'
                ,'share_shuoshuo','qrcode_attr','weixin_need_share','qq_qrcode','weixin_qrcode'
                ,'tt_need_share','tt_qrcode','tt_play_price','tt_share_template_id'])
            ->where(['is_deleted'=>0,'is_publish'=>1])
            ->find()->toArray();
        if(!$topicInfo){throw new Exception('数据错误');}
        $topicInfo['banner_img'] =  getThumbImg($topicInfo['banner_img'],400);
        $topicInfo['share_img'] =  getThumbImg($topicInfo['share_img']);
        $topicInfo['qq_qrcode'] =  !empty($topicInfo['qq_qrcode'])?getThumbImg($topicInfo['qq_qrcode']):'';
        $topicInfo['weixin_qrcode'] = !empty($topicInfo['weixin_qrcode'])? getThumbImg($topicInfo['weixin_qrcode']):'';
        $topicInfo['tt_qrcode'] = !empty($topicInfo['tt_qrcode'])? getThumbImg($topicInfo['tt_qrcode']):'';
        $topicInfo['topic'] = json_decode($topicInfo['topic'],true);
        $topicInfo['nickname_attr'] = json_decode($topicInfo['nickname_attr'],true);
        $topicInfo['headerimg_attr'] = json_decode($topicInfo['headerimg_attr'],true);
        $topicInfo['qrcode_attr'] = json_decode($topicInfo['qrcode_attr'],true);
        $topicInfo['share_content'] = !empty($topicInfo['share_content'])?$topicInfo['share_content']:'心理测评、趣味测评';
        $topicInfo['share_shuoshuo'] = !empty($topicInfo['share_shuoshuo'])?$topicInfo['share_shuoshuo']:'心理测评、趣味测评';

        $topicInfo['tt_play_price'] =  !empty($topicInfo['tt_play_price'])?floatval($topicInfo['tt_play_price']):0;
        if(empty($topicInfo['tt_play_price']) && $topicInfo['tt_need_share'] == 3){$topicInfo['tt_need_share'] = 0;
            $topicInfo['tt_play_price']=0;}


        //增加新测评题目逻辑
        $topicInfo['topic'] = array(
            'topic_type' => array(),
            'topic_question' => array(),
            'topic_question_img' => array(),
            'topic_answer' => array(),
        );

        if($topicInfo['questions']){
            foreach ($topicInfo['questions'] as $k=>$v){
                $topicInfo['topic']['topic_type'][] = 1;//选择题类型
                $topicInfo['topic']['topic_question'][] = $v['question'];//选择题
                $topicInfo['topic']['topic_question_img'][] = "";//选择题，无图片。需要后面加
                $question = json_decode($v['question_options'],true)['content'];
                $topicInfo['topic']['topic_answer'][] = $question;//选择题
            }
            unset($topicInfo['questions']);
        }




        //获取系统答题头像
        $logo = \app\common\model\Config::where(['config_key'=>'answer_logo'])->find();
        $topicInfo['system_logo'] = getThumbImg($logo['config_value']);


        $topicInfo['user_can_see_ad'] = true;
        /**
         * 若当前测评需要看广告出结果，需要判断当前用户已经看过广告的次数，然后判断是否超过后台系统限制的看广告次数
        若超过则后续任何测评当前用户均不可以通过看广告出结果
        统一处理三个平台的计算，因为用户id是唯一滴
         */
        $userInfo = User::where(['openid'=>Request::param('openid','')])
            ->field(['user_id','platform'])->find();
        if($userInfo != null){
            $share_type = 0;
            switch (intval($userInfo['platform'])){
                case 1:$share_type = $topicInfo['need_share'];break;
                case 2:$share_type = $topicInfo['weixin_need_share'];break;
                case 3:$share_type = $topicInfo['tt_need_share'];break;
            }

            if($share_type == 2){
                //查询当前用户今天所看广告次数
                $adCount = TopicLog::where(['user_id'=>$userInfo['user_id'],'topic_share_type'=>$share_type])
                    ->whereBetweenTime('created_at',intval(strtotime(date('Y-m-d',time()))))
                    ->count();
                //获取每天可以看广告的次数
                $dayAdCount = \app\common\model\Config::where(['config_key'=>'user_ad_count'])
                    ->field(['config_value'])->find();
                if($dayAdCount != null && $dayAdCount['config_value'] != null){
                    if($adCount >= $dayAdCount['config_value']){
                        $topicInfo['user_can_see_ad'] = false;
                    }
                }else{
                    $topicInfo['user_can_see_ad'] = false;
                }
            }
        }



        wapAjaxReturn(0,'查询成功',$topicInfo);
    }

    /**
     *
     * 获取测评结果
     */
    public function getResultImg(){
        $params = Request::post();
        try{
            //参数验证
            (new TopicLogic())->validateImgWithTopic($params,$topinInfo,$userInfo);


            $share_type = 0;
            switch (intval($params['platform'])){
                case 1:$share_type = $topinInfo['need_share'];break;
                case 2:$share_type = $topinInfo['weixin_need_share'];break;
                case 3:$share_type = $topinInfo['tt_need_share'];break;
            }
            //更新用户玩测评的log
            (new UserLogic())->userPlay($userInfo['user_id'],$topinInfo['topic_id'],$share_type);


            //通过规则计算当前返回图片的随机情况
            (new TopicLogic())->getImgWithTopic($params,$topinInfo);
        }catch(Exception $exception){
            wapAjaxReturn(400,'获取图片失败',$exception->getMessage());
            file_put_contents('log.txt',print_r($exception->getMessage(),1)."\r\n",FILE_APPEND);
        }

    }

    /**
     * 获取玩过的列表
     */
    public function getPlayLog(){
        $pageSize = Request::param('pageSize',10);
        $openid = Request::param('openid','');


        $userInfo = User::where('openid',$openid)->find();
        if(empty($userInfo)){
            wapAjaxReturn(500,'用户信息不存在');
        }

        $subQuery  = Db::table("qqxcx_topic_log")
            ->where(['user_id'=>$userInfo['user_id']])
            ->field(['topic_id','created_at'])
            ->order(['id'=>'desc'])
            ->buildSql();
        $topicLog = Db::table($subQuery."a")
            ->group("topic_id")
            ->paginate($pageSize)->toArray();
        $topicList = array();
        if($topicLog['data']){
            $ids = array_column($topicLog['data'],'topic_id');
            $topicList = Topic::whereIn("topic_id",$ids)
                ->field(['topic_id','banner_img','share_img','title','description'])
                ->select()->toArray();
            foreach ($topicList as &$v){
                $v['banner_img'] = getThumbImg($v['banner_img'],400);
                $v['share_img'] = getThumbImg($v['share_img'],400);
                $v['play_time'] = '';
                $v['play_time_int'] = 0;
                foreach ($topicLog['data'] as $v2){
                    if($v['topic_id'] ==$v2['topic_id']){
                        $v['play_time'] = date('Y-m-d',$v2['created_at']);
                        $v['play_time_int'] = $v2['created_at'];
                    }
                }
            }
        }
        if($topicList){
            array_multisort($topicList,SORT_DESC,array_column($topicList,'play_time_int'));
        }
        $topicLog['data'] = $topicList;
        wapAjaxReturn(0,'success',$topicLog);
    }

    /**
     * 随机推荐测评接口
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function randomTopic(){
        $topic = Db::name("topic")
            ->where(['is_deleted'=>0,'is_publish'=>1])
            ->field(['topic_id','banner_img','share_img','title','description','icon_type','base_game_count'])
            ->orderRand()->limit(10)->select();
        if($topic){
            $ids = array_column($topic,'topic_id');
            $topicTotalLog = TopicLog::whereIn("topic_id",$ids)->field(['topic_id','count(user_id) as count'])->group('topic_id')->select()->toArray();
            foreach ($topic as &$v){
                $v['game_count'] = $v['base_game_count'] * rand(5,10);
                if($topicTotalLog){
                    foreach ($topicTotalLog as $log){
                        if($v['topic_id'] ==$log['topic_id']){ $v['game_count'] = ($log['count']+$v['base_game_count'])* rand(5,10);break;}
                    }
                    unset($log);
                }
                if($v['game_count'] > 10000){$v['game_count'] = sprintf("%01.2f",$v['game_count']/10000).'万';}
                $v['banner_img'] = getThumbImg($v['banner_img'],400);
                $v['share_img'] = getThumbImg($v['share_img'],400);
                $v['icon'] = !empty($v['icon_type'])? Config::get('params.php_server') . '/static/images/icon_' . $v['icon_type'] .'.png' : '';
                unset($v['base_game_count']);
            }
        }
        wapAjaxReturn(0,'success',['topicList'=>$topic]);

    }


    /**
     * 获取关注公众号的信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWechatInfo(){
        $data = \app\common\model\Config::where("config_key = 'wechat_img' or config_key = 'wechat_desc' or config_key = 'customer_service' ")
            ->select()->toArray();
        if($data){
            $data = array_column($data,null,'config_key');
            wapAjaxReturn(0,'success',
                [
                    'desc'=>$data['wechat_desc']['config_value'],
                    'wechat'=>$data['customer_service']['config_value']]);
        }
        wapAjaxReturn(400,'error');
    }


    /**
     * 看广告，广告分销处理佣金数据
     */
    public function addMoneyFromAd(){
        $params = Request::post();
        file_put_contents('ad.log','进入广告分销'."\r\n",FILE_APPEND);
        file_put_contents('ad.log','进入广告分销'.print_r($params,1)."\r\n",FILE_APPEND);
        try{
            if(empty($params['topic_id'])){wapAjaxReturn(400,'不需要处理');}
            if(empty($params['openid'])){wapAjaxReturn(400,'不需要处理');}

            file_put_contents('ad.log','进入广告分销-基础数据'.print_r($params,1)."\r\n",FILE_APPEND);
            $userInfo = User::where('openid',$params['openid'])->find();
            if(empty($userInfo)){wapAjaxReturn(400,'当前用户不存在');}
            $topicInfo = Topic::where('topic_id',$params['topic_id'])->find();
            if(empty($topicInfo)){wapAjaxReturn(400,'测评数据不存在');}

            //处理当前测评是否有广告分销的内容
            (new UserDistribution())->dealAdDistribution($userInfo,$topicInfo);
            file_put_contents('ad.log','进入广告分销-处理成功'."\r\n",FILE_APPEND);
            wapAjaxReturn(0,'处理成功');
        }catch(Exception $exception){
            file_put_contents('ad.log','进入广告分销-执行失败'.print_r($exception->getMessage())."\r\n",FILE_APPEND);
            wapAjaxReturn(400,'处理失败',$exception->getMessage());
        }
    }


    /**
     * 佣金明细列表
     */
    public function distributionList(){
        $params = Request::get();
        if(empty($params['openid']) ){
            wapAjaxReturn(400,'参数错误');
        }
        $pageSize = Request::param('pageSize',10);

        $userInfo = User::find()->where(['openid'=>$params['openid']])->find();
        if($userInfo == null){wapAjaxReturn(400,'查询不到数据');}
        //其他的进行分页处理
        $list =
            UserDistribution::with(['userFrom'])->where(['user_id'=>$userInfo->user_id])
            ->where("((type = 4) or ( price_deal_staus = 1))")
            ->order(['created_at'=>'desc'])
//            ->field(['get_price','created_at','type','get_type','true_price'])
                ->paginate($pageSize)->toArray();
        if($list['data']){
            foreach ($list['data'] as &$v){
                $v['created_at'] = date('Y-m-d H:i:s',$v['created_at']);
                if($v['type'] == 4){
                    if($v['get_type'] == 0){$v['desc'] = '提现(未处理)';}
                    if($v['get_type'] == 1){$v['desc'] = '提现(已处理)';}
                }
                if($v['type'] == 1){$v['desc'] = '支付所得';}
                if($v['type'] == 2){$v['desc'] = '看广告所得';}
                if($v['type'] == 3){$v['desc'] = '测评奖励';}
                $v['get_price'] = $v['true_price'];
                $v['user_from_nickname'] = !empty($v['user_from'])?
                    urldecode($v['user_from']['nickname']):'';

                unset($v['id'],$v['order_id'],$v['topic_id'],$v['distribution_percent'],$v['user_from']);
            }
        }else{wapAjaxReturn(400,'暂无数据');}
        wapAjaxReturn(0,'success',['list'=>$list,'money'=>$userInfo->money,'total_money'=>$userInfo->total_money]);

    }



    /**
     * 申请提现
     */
    public function applyMoney(){
        $params = Request::post();
        Db::startTrans();
        try{
            if(empty($params['openid'])  || empty($params['real_name']) || empty($params['apply_account']) || empty($params['money'])
            || !is_numeric($params['money']) || $params['money'] <=0){
                throw new Exception('参数错误');
            }
            if(getPointLen($params['money']) > 2){
                throw new Exception('费用小数点最多2位');
            }
            if(strlen($params['real_name']) > 30){throw  new Exception('真实姓名长度超过限制');}
            if(strlen($params['apply_account']) > 60){throw  new Exception('申请提现账号长度超过限制');}

            //判断当前提现的金额是否满足可提现最小金额
            $configData = \app\common\model\Config::where(['config_key'=>'cash_money'])->find();
            if($configData != null && is_numeric($configData->config_value) && $configData->config_value > 0){
                if($configData->config_value > $params['money']){
                    throw new Exception('提现金额需要大于'.$configData->config_value.'元才可以提现');
                }
            }


            //查出用户信息
            $userInfo = User::where(['openid'=>$params['openid']])->find();
            if($userInfo == null){throw  new Exception('当前用户不存在');}
            if($params['money'] > $userInfo->money){throw new Exception('申请提现金额超过可提现金额');}

            //存储数据到分佣明细表中
            $distribution['user_id'] = $userInfo->user_id;
            $distribution['order_id'] = 0;
            $distribution['topic_id'] = 0;
            $distribution['distribution_percent'] = 0;
            $distribution['real_name'] = $params['real_name'];
            $distribution['origin_price'] = $params['money'];
            $distribution['get_price'] = $params['money'];
            $distribution['created_at'] = time();
            $distribution['type'] = 4;
            $distribution['get_type'] = 0;
            $distribution['true_price'] = $params['money'];
            $distribution['price_deal_staus'] = 0;

            $orderDistribution = new UserDistribution();
            $save = $orderDistribution->allowField(true)->save($distribution);
            if(!$save){throw  new Exception('分佣存储数据存储失败');}

            $distributionId = $orderDistribution->id;


            //存储数据到用户申请提现表中
            $apply['user_id'] = $userInfo->user_id;;
            $apply['price'] = $params['money'];
            $apply['ceated_at'] = time();
            $apply['apply_account'] = $params['apply_account'];
            $apply['distribution_id'] = $distributionId;
            $apply['real_name'] = $params['real_name'];

            $UserPrice = new UserPrice();
            $save2 = $UserPrice->allowField(true)->save($apply);
            if(!$save2){throw  new Exception('提现存储数据存储失败');}
            //用户表减去申请金额

            $userInfo->money = $userInfo->money - $params['money'];
            $userInfo->save();

            Db::commit();
            wapAjaxReturn(0,'成功');
        }catch(Exception $exception){
            Db::rollback();
            wapAjaxReturn(400,$exception->getMessage());
        }
    }


    //首页测评分类
    public function getTopicCate(){
        $data = TopicCate::where(['is_deleted'=>0,'show_index'=>1])
            ->field(['id','name','img'])
            ->select()->toArray();
        if($data){
            foreach ($data as &$v){
                $v['img'] = getThumbImg($v['img'],400);
            }
        }
        wapAjaxReturn(0,'success',$data);
    }


    //测评分类列表全部
    public function getTopicCateList(){
        $data = TopicCate::where(['is_deleted'=>0])
            ->field(['id','name'])
            ->select()->toArray();
        array_unshift($data,['id'=>0,'name'=>'全部']);
        wapAjaxReturn(0,'success',$data);
    }


    public function tokenUpdate(){
        $wechatInfo = (new \app\common\model\Config())->getWechatConfig();

        $wechatService = new WechatService($wechatInfo['wechat_token'],$wechatInfo['wechat_appid'],$wechatInfo['wechat_secret']);

    }


    public function getUrl(){
        //1、获取公众号配置
        $wechatInfo = (new \app\common\model\Config())->getWechatConfig();
        if(empty($wechatInfo['wechat_token']) || empty($wechatInfo['wechat_appid'])
            || empty($wechatInfo['wechat_secret']) || empty($wechatInfo['wechat_thumb_media_id'])
            || empty($wechatInfo['wechat_img_url'])){
            wapAjaxReturn(400,'公众号配置不完善');
        }

        $wechatService = new WechatService($wechatInfo['wechat_token'],$wechatInfo['wechat_appid'],$wechatInfo['wechat_secret']);
        $content = '{
            "action":"long2short",
            "long_url":"https://mp.weixin.qq.com/s?__biz=MzU1OTgxNjU2Ng==&mid=100000170&idx=1&sn=ec2d6eac76f4ee4a27dafa3d70cc5754&chksm=7c10cbb34b6742a5c9aaae727b4ad52b806227a0e3bb3827b43c57b85cb5f166363be91b2194#rd"
        }';
        $data = $wechatService->shortUrl($content);

        echo '<pre>';
        print_r($data);
    }

}
